#include "config.h"
#include "Arduino.h"
#include "gpio_cfg.h"
#include "time.h"
#include "mqtt.h"


#define LEDC_TIMER_13_BIT  13
#define LEDC_TIMER_8_BIT  8
// use 5000 Hz as a LEDC base frequency
#define LEDC_BASE_FREQ     1000

unsigned long last_systrg=0,now_systrg=0,real_last_systrg=0;
unsigned long interval_time=0;
uint8_t interval_1ms_times=0;
unsigned long last_trig =0;


//中断中不能print，print为阻塞，会导致不能及时喂狗导致重启。
void IRAM_ATTR HALL_callback()
{
    hall_count+=1;
    // Serial.printf("hall %d\n",hall_count);
    
}

void IRAM_ATTR BEE_interrupt_cbk()
{
    now_systrg=millis();
    if(now_systrg-real_last_systrg>200){//消抖
        interval_time=now_systrg-last_systrg;
        last_systrg=now_systrg;
        if((interval_time>bee_interve1)&&(interval_time<bee_interve2)){//2451 （2000，2500）蜂鸣器长鸣，渣盒新机器3566（3300，3700）
            interval_1ms_times+=1;
            }else interval_1ms_times=0;
        if((interval_time>280)&&(interval_time<500)){//294   蜂鸣器短鸣 打咖啡完成
            if((work_state == 26)){//清洗咖啡机指令
                if((now_systrg-last_trig>15000)){
                    last_trig = now_systrg;
                    if(pow_state == 1)pow_state = 0;
                    else pow_state = 1;
                }
            }
            else{
                work_state=0;
                }
            
        }
        bee_pluse=true;
    }
    real_last_systrg=now_systrg;
    
}

void IRAM_ATTR pow_interrupt_cbk()
{
    // Serial.println("Power_cbk.");
    // Serial.flush();
    digitalWrite(KEY6,HIGH);
    delay(200);
    digitalWrite(KEY6,LOW);
    delay(200);
    if(pow_state==1){
        esp_restart();
    }
    else{
        pow_state=1;
    }
}

void gpio_init(){
    pinMode(KEY1,OUTPUT);
    digitalWrite(KEY1,LOW);
    pinMode(KEY2,OUTPUT);
    digitalWrite(KEY2,LOW);
    pinMode(KEY3,OUTPUT);
    digitalWrite(KEY3,LOW);
    pinMode(KEY4,OUTPUT);
    digitalWrite(KEY4,LOW);
    pinMode(KEY5,OUTPUT);
    digitalWrite(KEY5,LOW);
    pinMode(KEY6,OUTPUT);
    digitalWrite(KEY6,LOW);//咖啡机按键初始化

    pinMode(VALVEL,OUTPUT);
    digitalWrite(VALVEL,LOW);//咖啡机电磁阀初始化
    pinMode(DOOR_SWICH,OUTPUT);
    digitalWrite(DOOR_SWICH,LOW);//咖啡机渣盒门模拟开关初始化

    pinMode(FLOW_HALL,INPUT);
    attachInterrupt(FLOW_HALL,HALL_callback,CHANGE);//流量计输入初始化
    pinMode(BEE_INPUT,INPUT_PULLDOWN);
    attachInterrupt(BEE_INPUT,BEE_interrupt_cbk,RISING);//蜂鸣器输入监控初始化

    ledcSetup(PWM_CHANNEL1, LEDC_BASE_FREQ, LEDC_TIMER_8_BIT);
    ledcAttachPin(PUMP1, PWM_CHANNEL1);
    set_pump_speed(PWM_CHANNEL1,0);
    ledcSetup(PWM_CHANNEL2, LEDC_BASE_FREQ, LEDC_TIMER_8_BIT);
    ledcAttachPin(PUMP2, PWM_CHANNEL2);
    set_pump_speed(PWM_CHANNEL2,0);
    ledcSetup(PWM_CHANNEL3, LEDC_BASE_FREQ, LEDC_TIMER_8_BIT);
    ledcAttachPin(PUMP3, PWM_CHANNEL3);
    set_pump_speed(PWM_CHANNEL3,0);
    ledcSetup(PWM_CHANNEL4, LEDC_BASE_FREQ, LEDC_TIMER_8_BIT);
    ledcAttachPin(PUMP4, PWM_CHANNEL4);
    set_pump_speed(PWM_CHANNEL4,0);//水泵初始化

    //screen input init
}

/**
 * @brief 流量计监控（废弃，改用回调函数）
 * 
 */
// void hall_loop(void *pvParameters)//
// {
//     uint8_t gpio_level=LOW;
//     while(1){
//         if(gpio_level!=digitalRead(FLOW_HALL)){
//             if(gpio_level==LOW) gpio_level=HIGH;
//             else gpio_level=LOW;
//             hall_count+=1;
//         }
//         delay(1);
//     }
// }

/**
 * @brief Set the pump speed object封装的设置水泵速度函数，由pwm控制
 * 
 * @param channel 
 * @param value 
 * @param valueMax 
 */
void set_pump_speed(uint8_t channel, uint32_t value, uint32_t valueMax) {
    // calculate duty, 8191 from 2 ^ 13 - 1
    uint32_t duty = (255 / valueMax) * min(value, valueMax);
    // write duty to LEDC
    ledcWrite(channel, duty);   
}
/**
 * @brief 控制时间初始化
 * 从内存中读取各个控制参数
 * 
 */

void controll_time_init()
{
    pref.begin("config");
    if(pref.isKey("natie_time"))
    {
        natie_time=pref.getUInt("natie_time");
    }
    else pref.putUInt("natie_time",natie_time);
    if(pref.isKey("kabuqinuo_time"))
    {
        kabuqinuo_time=pref.getUInt("kabuqinuo_time");
    }
    else pref.putUInt("kabuqinuo_time",kabuqinuo_time);
    if(pref.isKey("yishi_time"))
    {
        yishi_time=pref.getUInt("yishi_time");
    }
    else pref.putUInt("yishi_time",yishi_time);
    if(pref.isKey("clean_time"))
    {
        clean_time=pref.getUInt("clean_time");
    }
    else pref.putUInt("clean_time",clean_time);
    if(pref.isKey("yeru_pluse"))
    {
        yeru_pluse=pref.getUInt("yeru_pluse");
    }
    else pref.putUInt("yeru_pluse",yeru_pluse);
    if(pref.isKey("work_times"))
    {
        work_times=pref.getUInt("work_times");
    }
    else pref.putUInt("work_times",work_times);
    if(pref.isKey("channel1_pluse"))
    {
        channel1_pluse=pref.getUInt("channel1_pluse");
    }
    else pref.putUInt("channel1_pluse",channel1_pluse);

    if(pref.isKey("bee_interve1"))
    {
        bee_interve1=pref.getUInt("bee_interve1");
    }
    else pref.putUInt("bee_interve1",bee_interve1);

    if(pref.isKey("bee_interve2"))
    {
        bee_interve2=pref.getUInt("bee_interve2");
    }
    else pref.putUInt("bee_interve2",bee_interve2);


    if(pref.isKey("machine_type"))
    {
        machine_type=pref.getUInt("machine_type");
    }
    else pref.putUInt("machine_type",machine_type);
    mqtt_log("nt_time:%d kb_time:%d ys_time%d clean_time:%d ye_time:%d work_times:%d\n",natie_time,kabuqinuo_time,yishi_time,clean_time,yeru_pluse,work_times);
    Serial.printf("nt_time:%d kb_time:%d ys_time%d clean_time:%d ye_time:%d work_times:%d\n",natie_time,kabuqinuo_time,yishi_time,clean_time,yeru_pluse,work_times);
    pref.end();
}


/**
 * @brief 按键监控进程
 * 
 * @param pvParameters 
 */

void key_monitor(void *pvParameters){
    uint8_t bee=0;
    last_systrg=millis();
    while(1){
        if(bee_pluse){  //蜂鸣器事件
            mqtt_log("bee trigger,interval %ld ms,last_trg %ld,now %ld,interval_1ms_times%d\n",interval_time,last_trig,now_systrg,interval_1ms_times);
            Serial.printf("bee trigger,interval %ld ms,last_trg %ld,now %ld,interval_1ms_times%d\n",interval_time,last_trig,now_systrg,interval_1ms_times);
            if(interval_1ms_times>=3){  //如果间隔1ms的次数大于3，就开关门
                door_reset=false;
            }
            bee_pluse=false;
        }
        delay(10);
    }
}